package com.heima.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;


@Service
public class ApUserServiceImpl implements IApUserService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto loginDto) {
        if(StringUtils.isEmpty(loginDto.getPhone()) || StringUtils.isEmpty((loginDto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String dbPassword = apUser.getPassword();
        String inputPassword = loginDto.getPassword() + apUser.getSalt();// salt加密 md5加密
        String inputMd5 = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!inputMd5.equals(dbPassword)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        JSONObject jsonObject = new JSONObject();
        apUser.setSalt(null);
        jsonObject.put("user",apUser);
        jsonObject.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));

        return ResponseResult.okResult(jsonObject);
    }
}
